package org.cigo.fworld.widget;

import java.util.ArrayList;
import java.util.List;

import org.cigo.fworld.R;

import android.content.Context;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 成员添加控件
 * 
 * @author goby
 */
public class ContactScrollView extends ScrollView implements
OnItemClickListener {
	private Context mContext;
	private LayoutInflater mInflater;
	private LinearLayout mMainLayout;
	private LinearLayout mLastLayout;
	private List<LinearLayout> mSubLayoutList = new ArrayList<LinearLayout>();
	private AutoCompleteTextView mAutoCompleteTv;  
	private int mAutoCompleteTvWidth = 30;  
	private int mLinearLayoutIndex = -1;
	private int mLineWidth;
	private int mItemLayoutResourceId;		//每行的LinearLayout的布局文件id
	private int mCurrLineWidth = 0;  
	private boolean mHaveNewLine = true;
	private int mBackgroundColor = 0;
	private int mDeleteImageView = 0;
	private int mItemTextView;
	
	public ContactScrollView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	public ContactScrollView(Context context, AttributeSet attrs){
		super(context, attrs);
		init(context);
	}

	public ContactScrollView(Context context){
		super(context);
		init(context);
	}

	/**  
	 * 初始化ScrollView下的主LinearLayout,第一个LinearLayout,和AutoCompleteTextView  
	 * @param context  
	 */  
	private void init(Context context){
		mContext = context;
		mInflater = LayoutInflater.from(context);
		mMainLayout = new LinearLayout(mContext);
		mMainLayout.setOrientation(LinearLayout.VERTICAL);  
		mMainLayout.setLayoutParams( new LinearLayout.LayoutParams(  
				LinearLayout.LayoutParams.FILL_PARENT,  
				LinearLayout.LayoutParams.WRAP_CONTENT  
		));
		this.addView(mMainLayout);

		LinearLayout firstLayout = createSubLinearLayout();  
		mSubLayoutList.add(firstLayout);  
		mLastLayout = firstLayout;  
		mLastLayout.setBackgroundColor(mContext.getResources().getColor(mBackgroundColor));  

		//将AutoCompleteTextView加入到第一个LinearLayout  
		mAutoCompleteTv = new AutoCompleteTextView(mContext);  
		mAutoCompleteTv.setOnItemClickListener(this);  
		mAutoCompleteTv.setWidth(mAutoCompleteTvWidth);  
		firstLayout.addView(mAutoCompleteTv);  

		//将创建的第一个linearLayout 加入到mainLayout中  
		mMainLayout.addView(firstLayout);  
	}

	/**  
	 * 新建一行:新建一个LinearLayout  
	 * @return  
	 */  
	private LinearLayout createSubLinearLayout(){  
		LinearLayout layout = new LinearLayout(mContext);  
		LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(  
				LinearLayout.LayoutParams.FILL_PARENT,  
				LinearLayout.LayoutParams.WRAP_CONTENT);  
		layout.setOrientation(LinearLayout.HORIZONTAL);  
		layout.setLayoutParams(lp1);  
		layout.setGravity(Gravity.CENTER_VERTICAL);  

		mLinearLayoutIndex++;  
		return layout;  
	}  

	/**  
	 * 设置Item布局资源id  
	 * @param resourceId  
	 */  
	public void setItemLayout(int resourceId){  
		this.mItemLayoutResourceId = resourceId;  
	}

	public void setBackgroundColor(int resourceId){
		this.mBackgroundColor = resourceId;
	}

	public void setDeleteImageView(int resourceId){
		this.mDeleteImageView = resourceId;
	}
	
	public void setItemTextView(int resourceId){
		this.mItemTextView = resourceId;
	}

	/**  
	 * 初始化AutoCompleteTextView的数据源  
	 * @param data  
	 */  
	public void initAutoCompleteTextView(String[] data){  
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext,  
				android.R.layout.simple_dropdown_item_1line, data);  
		mAutoCompleteTv.setAdapter(adapter);  
	}

	/**  
	 *  
	 * 重新添加所有的Item  
	 *  
	 * @param itemList  
	 */  
	private void reAddAllItem(List<View> itemList){  
		LinearLayout firstLayout = createSubLinearLayout();  
		mSubLayoutList.add(firstLayout);  
		mLastLayout = firstLayout;  
		mMainLayout.addView(firstLayout);  
		mCurrLineWidth = 0;  
		for(View item:itemList){  
			int childCount = mLastLayout.getChildCount();  
			int itemWidth = item.getWidth();  
			if(childCount==0){  
				mLastLayout.addView(item, 0);  
				item.setTag(mLastLayout);  
				mCurrLineWidth += itemWidth+10;  
			}else{  
				if(mLineWidth-mCurrLineWidth<itemWidth+10){  //如果当前行不足以显示该Item,要做换行处理  
					mLastLayout = createSubLinearLayout();  
					mLastLayout.addView(item);  
					item.setTag(mLastLayout);  

					mMainLayout.addView(mLastLayout);  
					mSubLayoutList.add(mLastLayout);  

					mCurrLineWidth = itemWidth+10;  
					mHaveNewLine = true;  
				}else{  

					mLastLayout.addView(item, childCount);  
					item.setTag(mLastLayout);  
					mCurrLineWidth += itemWidth+10;  
					mHaveNewLine = false;  
				}  
			}  
		}  

		//最后添加autocompleteTextView  
		mLastLayout.addView(mAutoCompleteTv);  
	}  

	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		//选中后，往当前lastLinearLayout中添加一个Item  
		String value = mAutoCompleteTv.getText().toString();  
		addItem(value);  
		mAutoCompleteTv.setText("");  
	}

	private void addItem(String value) {
		mLineWidth = mLastLayout.getWidth();
		final LinearLayout item = (LinearLayout)mInflater.inflate(mItemLayoutResourceId,null);  

		final ImageView deleteIv = (ImageView)item.findViewById(mDeleteImageView);  
		deleteIv.setVisibility(View.GONE);  
		deleteIv.setOnClickListener(new OnClickListener() { 
			public void onClick(View v) {  
				LinearLayout layout = (LinearLayout)item.getTag();  
				layout.removeView(item);  
				List<View> itemList =new ArrayList<View>();  
				int mainLayoutChildCount = mMainLayout.getChildCount();  
				for(int i = 0 ;i< mainLayoutChildCount;i++){  
					LinearLayout linearLayout = (LinearLayout)mMainLayout.getChildAt(i);  
					int count = linearLayout.getChildCount();  
					for(int j =0;j<count;j++){  
						View itemLayout = (View)linearLayout.getChildAt(j);  
						if(!(itemLayout instanceof AutoCompleteTextView)){  
							itemList.add(itemLayout);  
						}  
					}  
					linearLayout.removeAllViews();  
				}  
				mMainLayout.removeAllViews();  
				mSubLayoutList.clear();  
				reAddAllItem(itemList);  
			}  
		});
		
		item.setOnClickListener(new OnClickListener(){  
            public void onClick(View v) {  
                if(deleteIv.getVisibility() == View.GONE){  
                    deleteIv.setVisibility(View.VISIBLE);  
                    item.setBackgroundColor(mContext.getResources().getColor(R.color.color_orange));  
                }else{  
                    deleteIv.setVisibility(View.GONE);  
                    item.setBackgroundColor(mContext.getResources().getColor(R.color.color_light));  
                }  
            }  
        }); 
		
	    TextView itemTv = (TextView)item.findViewById(mItemTextView);  
        int itemWidth = (int)getFontWidth(value, (int)itemTv.getTextSize(), mContext)+30;  
        
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(itemWidth,  
                LinearLayout.LayoutParams.WRAP_CONTENT);  
        params.setMargins(10, 10, 10, 10);  
  
        item.setLayoutParams(params);  
        itemTv.setText(value);  
  
        Log.i("test","autoCompleteTv.width="+mAutoCompleteTv.getWidth());  
        int childCount = mLastLayout.getChildCount();  
        
        if(childCount==1){  
        	mLastLayout.addView(item, 0);  
        	mCurrLineWidth += itemWidth+10;  
        }else{  
        	if(mLineWidth-mCurrLineWidth<itemWidth+10){  //如果当前行不足以显示该Item,要做换行处理  
        		mLastLayout.removeView(mAutoCompleteTv);  
        		mLastLayout = createSubLinearLayout();  
        		mLastLayout.addView(item);  
        		mLastLayout.addView(mAutoCompleteTv);  
        		mMainLayout.addView(mLastLayout);  
        		mSubLayoutList.add(mLastLayout);  
        		mCurrLineWidth = itemWidth+10;  
        		mHaveNewLine = true;  
        	}else{  
        		mLastLayout.addView(item, childCount-1);  
        		mCurrLineWidth += itemWidth+10;  
        		mHaveNewLine = false;  
        	}  
        }
        mLastLayout.setTag(mLinearLayoutIndex);  
        item.setTag(mLastLayout);
        
        //如果目前该行剩余的宽度不足以显示autoCompleteTextView就要做换行处理  
        if( !mHaveNewLine && mLineWidth-mCurrLineWidth<mAutoCompleteTv.getWidth()-100){  
                //将autoCompleteTextView从lastLinearLayout中remove掉  
                mLastLayout.removeView(mAutoCompleteTv);  
                //新建一个LinearLayout,将autoCompleteTextView添加到此LinaerLayout  
                mLastLayout = createSubLinearLayout();  
                mLastLayout.addView(mAutoCompleteTv);  
                mMainLayout.addView(mLastLayout);  
  
                mSubLayoutList.add(mLastLayout);  
                mCurrLineWidth = 0;  
        }
	}

	public List<String> getContacts(){
		List<String> contacts = new ArrayList<String>();
		for(LinearLayout layout:mSubLayoutList){
			TextView itemTv = (TextView)layout.findViewById(mItemTextView); 
			String str = (String) itemTv.getText();
			if(str.length() > 0){
				contacts.add(str);
			}
		}
		return contacts;
	}
	
	private static float getFontWidth(String value, int textSize, Context context) {
		TextPaint tp = new TextPaint();
		tp.setTextSize(textSize);
		return tp.measureText(value);
	}
}
